package com.lalameow.serverlogin.network.handler;

import com.lalameow.packet.BasePack;
import com.lalameow.packet.enumtype.PackType;
import com.lalameow.packet.packImpl.PingPack;
import com.lalameow.serverlogin.ServerLoginMod;
import com.lalameow.serverlogin.client.ClientProxy;
import com.lalameow.serverlogin.common.CommonProxy;
import com.lalameow.serverlogin.network.ClientState;
import com.lalameow.serverlogin.network.McLoginClient;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;


/**
 * Created with IntelliJ IDEA.
 * 创建人: 陈刚
 * 日期: 2018/5/7
 * 时间: 20:37
 * 功能：请进行修改
 */
@SideOnly(Side.CLIENT)
public class ClientHandler extends SimpleChannelInboundHandler<BasePack> {

    ClientProxy clientProxy=(ClientProxy) ServerLoginMod.proxy;
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            switch (e.state()) {
                case WRITER_IDLE:
                    PingPack pingMsg=new PingPack();
                    ctx.writeAndFlush(pingMsg);
                    break;
                default:
                    break;
            }
        }
    }
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, BasePack msg) throws Exception {
//        System.out.println("msg = " + msg);
        clientProxy.packQueue.offer(msg);

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        McLoginClient.clientState= ClientState.EXCEPTION;
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        McLoginClient.clientState= ClientState.EXCEPTION;
    }
}
